package com.lebang.service.sys;

import com.lebang.component.RedisClient;
import com.lebang.domain.DownFailConfig;
import com.lebang.entity.RequestHeaders;
import com.lebang.example.DownFailConfigExample;
import com.lebang.service.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * down_fail_config
 *
 * @Author hwq
 * @Date 2020-07-09
 */
@Service
public class DownFailConfigService extends BaseService<DownFailConfig, Long, DownFailConfigExample> {
    @Autowired
    private RedisClient redisClient;
    private static final String LOCK_KEY="lock:pull:download:";

    public void addFailCount(int count, RequestHeaders requestHeaders) {
        count++;
        DownFailConfigExample example = new DownFailConfigExample();
        example.setOrderByClause("fail_count desc");
        List<DownFailConfig> downFailConfigs = this.selectByExample(example);
        for (DownFailConfig vo : downFailConfigs) {
            if (count == vo.getFailCount()) {
                redisClient.setex(LOCK_KEY + requestHeaders.getUserid(), "1", vo.getFailSecond() * 60);
                redisClient.setex(LOCK_KEY + requestHeaders.getImei(), "1", vo.getFailSecond() * 60);
                break;
            }
        }
    }

    /**
     * 验证是否有存在放弃次数过多 有则返回秒数
     * @param requestHeaders
     * @return
     */
    public Long checkFail(RequestHeaders requestHeaders){
        if(redisClient.exists(LOCK_KEY + requestHeaders.getUserid())){
            return redisClient.ttl(LOCK_KEY + requestHeaders.getUserid());
        }
        if(redisClient.exists(LOCK_KEY + requestHeaders.getImei())){
            return redisClient.ttl(LOCK_KEY + requestHeaders.getImei());
        }
        return 0L;
    }

    public DownFailConfig getFail(int count, RequestHeaders requestHeaders) {
        count++;
        DownFailConfigExample example = new DownFailConfigExample();
        example.setOrderByClause("fail_count asc");
        List<DownFailConfig> downFailConfigs = this.selectByExample(example);
        for (DownFailConfig vo : downFailConfigs) {
            if (vo.getFailCount()>count) {
                return vo;
            }
        }
        return downFailConfigs.get(downFailConfigs.size()-1);
    }
}
